package com.sl.au.controller;

import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.sl.au.entity.EventRegister;
import com.sl.au.entity.EventReport;
import com.sl.au.entity.User;
import com.sl.au.entity.UserSingle;
import com.sl.au.entity.EventTask;
import com.sl.au.entity.EventToEvaluateUser;
import com.sl.au.entity.EventType;
import com.sl.au.entity.Grading;
import com.sl.au.entity.GridAreaInfo;
import com.sl.au.entity.Option;
import com.sl.au.entity.PartBaseInfo;
import com.sl.au.service.EventRegisterService;
import com.sl.au.service.EventReportOuterService;
import com.sl.au.service.OperateLogService;
import com.sl.au.service.GridAreaInfoService;
import com.sl.au.service.GridUserDetailsService;
import com.sl.au.service.IdentifyService;
import com.sl.au.service.OptionService;
import com.sl.au.service.PartBaseInfoService;
import com.sl.au.service.EventTypeService;
import com.sl.au.service.GradingService;
import com.sl.au.service.UserService;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@RestController
@RequestMapping(value = "/ui/eventReportOuter")
public class EventReportOuterController extends BaseController {

	@Autowired
	private OptionService optionService;
	@Autowired
	private GridAreaInfoService gridAreaInfoService;
	@Autowired
	private EventReportOuterService eventReportOuterService;
	@Autowired
	private EventTypeService eventTypeService;
	@Autowired
	private UserService userService;
	@Autowired
	private PartBaseInfoService partBaseInfoService;
	@Autowired
	private GridUserDetailsService gridUserDetailsService;
	@Autowired
	private OperateLogService operateLogService;
	
	@Autowired
	private EventRegisterService eventRegisterService;
	@Autowired
	private GradingService gradingService;
	@Autowired
	IdentifyService identifyService;
	
	@RequestMapping(value = "/saveReportByOuter", method = RequestMethod.POST)
	public Map<String, Object> saveReportByOuter() {
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject object = JSONObject.fromObject(request.getParameter("eventReport"));
		EventReport eventReport = (EventReport) JSONObject.toBean(object, EventReport.class);

		User user = this.userService.getRepository().findByName("admin");
		// 标注事件来源
		if (eventReport.getReportEventOrg() != null) {
			Option org = this.optionService.getRepository().findByGroupAndExtended1("事件上报来源",
					eventReport.getReportEventOrg().getExtended1());
			if (org != null) {
				eventReport.setReportEventOrg(org);
			} else {
				map.put("code", "未找到事件源类型");
				return map;
			}
		} else {
			map.put("code", "未找到事件源类型");
			return map;
		}

		// 上报类型
		if (eventReport.getReportEventType() != null) {
			List<EventType> type = this.eventTypeService.getRepository()
					.findByName(eventReport.getReportEventType().getEventName());
			if (type != null && type.size() > 0) {
				eventReport.setReportEventType(type.get(0));
			} else {
				map.put("code", "未找到事件类型");
				return map;
			}
		} else {
			map.put("code", "未找到事件类型");
			return map;
		}
		String url = "";
		// 前端图片压缩上传功能
		if (eventReport.getReportImgAdress() != null
				&& eventReport.getReportImgAdress().contains("data:image/png;base64")) {
			String[] imgl = eventReport.getReportImgAdress().split(",");
			eventReport.setReportImgAdress("");
			url = this.saveImgWithBase64(this.fileUploadPath, "img/eventReport", eventReport.getId() + ".png",
					imgl[imgl.length - 1]);
			eventReport.setReportImgAdress(url);
		}

		eventReport.setReportUser(user);
		eventReport.setReportAccTime(new Date());
		List<Option> list = optionService.getRepository().findByGroupAndTitle("事件上报状态", "初始化");
		if (list != null && list.size() > 0) {
			eventReport.setReportEventVariable(list.get(0));
		} else {
			map.put("code", "未知错误");
			return map;
		}
		List<Option> ls = optionService.getRepository().findByGroupAndTitle("事件上报属性状态", "真实有效");
		if (ls != null && ls.size() > 0) {
			eventReport.setReportEventAttrVariable(ls.get(0));
		} else {
			map.put("code", "未知错误");
			return map;
		}

		GridAreaInfo gridAreaInfo = gridAreaInfoService.GetGridAreaInfoByCoordinate(eventReport.getLongitude(),
				eventReport.getLatitude());
		eventReport.setReportEventToNetGrid(gridAreaInfo);

		// 事件源上报的日志信息
		EventTask reportTask = new EventTask();
		reportTask.setEventId(eventReport.getId());
		reportTask.setEventTaskMemo(eventReport.getReportEventOrg().getTitle());
		reportTask.setEventTaskOperate("上报事件源");
		reportTask.setEventTaskState(eventReport.getReportEventVariable());
		reportTask.setEventTaskTime(new Date());
		reportTask.setEventTaskUser(user);
		eventReportOuterService.saveAll(eventReport, reportTask);

		map.put("code", "上报成功");
		return map;
	}
	@RequestMapping(value = "/outerEventReport", method = RequestMethod.POST)
	public Map<String, Object> outerEventReport() {
		Map<String, Object> map = new HashMap<String, Object>();

		try {
			EventReport eventReport = new EventReport();

			User user = this.userService.getRepository().findByName("admin");
			// 标注事件来源
			if (request.getParameter("eventOrg") != null) {
				Option org = this.optionService.getRepository().findByGroupAndExtended1("事件上报来源",
						URLDecoder.decode(request.getParameter("eventOrg"), "utf-8"));
				if (org != null) {
					eventReport.setReportEventOrg(org);
				} else {
					map.put("code", "未找到事件源类型");
					return map;
				}
			} else {
				map.put("code", "未找到事件源类型");
				return map;
			}

			// 上报类型
			if (request.getParameter("eventType") != null) {
				List<EventType> type = this.eventTypeService.getRepository()
						.findByName(URLDecoder.decode(request.getParameter("eventType"),"utf-8"));
				if (type != null && type.size() > 0) {
					eventReport.setReportEventType(type.get(0));
					eventReport.setRealReportEventType(type.get(0));
				} else {
					map.put("code", "未找到事件类型");
					return map;
				}
			} else {
				map.put("code", "未找到事件类型");
				return map;
			}

			// 上报图片
			String url = "";
			if (request.getParameter("eventImg") != null
					&& request.getParameter("eventImg").contains("data:image/png;base64")) {
				String[] imgl = request.getParameter("eventImg").split(",");
				url = this.saveImgWithBase64(this.fileUploadPath, "img/eventReport", eventReport.getId() + ".png",
						imgl[imgl.length - 1]);
				if(StringUtils.hasText(url)){
					map.put("code", "上传图片格式不正确");
					return map;
				}
				eventReport.setReportImgAdress(url);
			}
			// 上报内容
			if (request.getParameter("eventContent") != null) {
				eventReport.setReportContent(URLDecoder.decode(request.getParameter("eventContent"),"utf-8"));
			}
			// 上报备注
			if (request.getParameter("eventMemo") != null) {
				eventReport.setReportMemo(URLDecoder.decode(request.getParameter("eventMemo"),"utf-8"));
			}
			// 上报地址
			if (request.getParameter("eventAdress") != null) {
				eventReport.setReportAdress(URLDecoder.decode(request.getParameter("eventAdress"),"utf-8"));
			}
			// 上报经度
			if (request.getParameter("longitude") != null) {
				try {
					double longitude = Double.parseDouble(request.getParameter("longitude"));
					eventReport.setLongitude(longitude);
				} catch (Exception ex) {
					map.put("code", "经度错误");
					return map;
				}
			}else
			{
				map.put("code", "必须填写经度");
				return map;
			}
			// 上报纬度
			if (request.getParameter("latitude") != null) {
				try {
					double latitude = Double.parseDouble(request.getParameter("latitude"));
					eventReport.setLatitude(latitude);
				} catch (Exception ex) {
					map.put("code", "纬度错误");
					return map;
				}
			}else{
				map.put("code", "必须填写纬度");
				return map;
			}

			eventReport.setReportUser(user);
			eventReport.setReportAccTime(new Date());
			List<Option> list = optionService.getRepository().findByGroupAndTitle("事件上报状态", "初始化");
			if (list != null && list.size() > 0) {
				eventReport.setReportEventVariable(list.get(0));
			} else {
				map.put("code", "未知错误");
				return map;
			}
			List<Option> ls = optionService.getRepository().findByGroupAndTitle("事件上报属性状态", "真实有效");
			if (ls != null && ls.size() > 0) {
				eventReport.setReportEventAttrVariable(ls.get(0));
			} else {
				map.put("code", "未知错误");
				return map;
			}

			GridAreaInfo gridAreaInfo = gridAreaInfoService.GetGridAreaInfoByCoordinate(eventReport.getLongitude(),
					eventReport.getLatitude());
			eventReport.setReportEventToNetGrid(gridAreaInfo);

			// 事件源上报的日志信息
			EventTask reportTask = new EventTask();
			reportTask.setEventId(eventReport.getId());
			reportTask.setEventTaskMemo(eventReport.getReportEventOrg().getTitle());
			reportTask.setEventTaskOperate("上报事件源");
			reportTask.setEventTaskState(eventReport.getReportEventVariable());
			reportTask.setEventTaskTime(new Date());
			reportTask.setEventTaskUser(user);
			eventReportOuterService.saveAll(eventReport, reportTask);
			
			this.operateLogService.log(user, "接口上报", "外部上报:"+eventReport.getReportAccTime().toString()+",发生:"+eventReport.getReportEventType().getEventName()+",详细情况:"+eventReport.getReportContent()+",地点:"+eventReport.getReportAdress()+"经度:"+eventReport.getLongitude()+",纬度:"+eventReport.getLatitude());
		} catch (Exception ex) {
			map.put("code", "未知错误");
			return map;
		}

		map.put("code", "上报成功");
		return map;
	}

	@RequestMapping(value = "/outerEventReportByPart", method = RequestMethod.POST)
	public Map<String, Object> outerEventReport1() {
		Map<String, Object> map = new HashMap<String, Object>();
		
		try {
			EventReport eventReport = new EventReport();
			
			User user = this.userService.getRepository().findByName("admin");
			// 标注事件来源
			if (request.getParameter("eventOrg") != null) {
				Option org = this.optionService.getRepository().findByGroupAndExtended1("事件上报来源",
						URLDecoder.decode(request.getParameter("eventOrg"), "utf-8"));
				if (org != null) {
					eventReport.setReportEventOrg(org);
				} else {
					map.put("code", "未找到事件源类型");
					return map;
				}
			} else {
				map.put("code", "未找到事件源类型");
				return map;
			}
			
			// 上报类型
			EventType eventType = null;
			if (request.getParameter("eventType") != null) {
				List<EventType> type = this.eventTypeService.getRepository()
						.findByName(URLDecoder.decode(request.getParameter("eventType"),"utf-8"));
				if (type != null && type.size() > 0) {
					eventType = type.get(0);
				} else {
					map.put("code", "未找到事件类型");
					return map;
				}
			} else {
				map.put("code", "未找到事件类型");
				return map;
			}
			
			eventReport.setReportEventType(eventType);
			eventReport.setRealReportEventType(eventType);
			// 上报图片
//			String url = "";
//			if (request.getParameter("eventImg") != null
//					&& request.getParameter("eventImg").contains("data:image/png;base64")) {
//				String[] imgl = request.getParameter("eventImg").split(",");
//				url = this.saveImgWithBase64(this.fileUploadPath, "img/eventReport", eventReport.getId() + ".png",
//						imgl[imgl.length - 1]);
//				if(StringUtils.hasText(url)){
//					map.put("code", "上传图片格式不正确");
//					return map;
//				}
//				eventReport.setReportImgAdress(url);
//			}
			// 上报内容
			if (request.getParameter("eventContent") != null) {
				eventReport.setReportContent(URLDecoder.decode(request.getParameter("eventContent"),"utf-8"));
			}
			// 上报备注
			if (request.getParameter("eventMemo") != null) {
				eventReport.setReportMemo(URLDecoder.decode(request.getParameter("eventMemo"),"utf-8"));
			}
			
			PartBaseInfo partBaseInfo = null;
			List<PartBaseInfo> listPart = new ArrayList<PartBaseInfo>();
			if(request.getParameter("deviceIdentify") != null) {
				listPart = partBaseInfoService.getRepository().findPartBaseInfoByDeviceIdentify(URLDecoder.decode(request.getParameter("deviceIdentify"),"utf-8"));
				if(listPart.size() == 0) {
					map.put("code", "设备编码错误");
					return map;
				}else if(listPart.size() > 1) {
					map.put("code", "设备编码存在多个部件信息");
					return map;
				}
				partBaseInfo = listPart.get(0);
			}
			
			Date accTime = new Date();
			
			// 上报地址
			eventReport.setReportAdress(partBaseInfo.getPartAdress());
			
			eventReport.setLongitude(partBaseInfo.getLongitude());
			eventReport.setLatitude(partBaseInfo.getLatitude());
			
			eventReport.setReportUser(user);
			eventReport.setReportAccTime(accTime);
			List<Option> list = optionService.getRepository().findByGroupAndTitle("事件上报状态", "已受理");
			if (list != null && list.size() > 0) {
				eventReport.setReportEventVariable(list.get(0));
			} else {
				map.put("code", "未知错误");
				return map;
			}
			List<Option> ls = optionService.getRepository().findByGroupAndTitle("事件上报属性状态", "真实有效");
			if (ls != null && ls.size() > 0) {
				eventReport.setReportEventAttrVariable(ls.get(0));
			} else {
				map.put("code", "未知错误");
				return map;
			}
			
			GridAreaInfo gridAreaInfo = gridAreaInfoService.GetGridAreaInfoByCoordinate(eventReport.getLongitude(),
					eventReport.getLatitude());
			eventReport.setReportEventToNetGrid(gridAreaInfo);
			
			// 事件源上报的日志信息
			EventTask reportTask = new EventTask();
			reportTask.setEventId(eventReport.getId());
			reportTask.setEventTaskMemo(eventReport.getReportEventOrg().getTitle());
			reportTask.setEventTaskOperate("上报事件源");
			reportTask.setEventTaskState(eventReport.getReportEventVariable());
			reportTask.setEventTaskTime(accTime);
			reportTask.setEventTaskUser(user);
//			eventReportOuterService.saveAll(eventReport, reportTask);
			
			//详细事件
			EventRegister eventRegister = new EventRegister();
			
			//设置内部事件经纬度
			eventRegister.setLatitude(partBaseInfo.getLatitude());
			eventRegister.setLongitude(partBaseInfo.getLongitude());
			
			eventRegister.setRegisterEventAccTime(accTime);
			eventRegister.setRegisterEventReportTime(accTime);
			eventRegister.setRegisterEventAdress(partBaseInfo.getPartAdress());
			eventRegister.setRegisterEventName("智能部件上报");
			eventRegister.setRegisterEventContent(URLDecoder.decode(request.getParameter("eventContent"),"utf-8"));
			eventRegister.setRegisterEventMemo(URLDecoder.decode(request.getParameter("eventMemo"),"utf-8"));

			eventRegister.setRegisterEventCreateUser(user);
			eventRegister.setRegisterEventType(eventType);
			
			eventRegister.setRegisterEventToPartBaseInfo(partBaseInfo);
			eventRegister.setRegisterEventToReportEvent(eventReport);
			
			eventRegister.setRegisterEventToNetGrid(gridAreaInfo);
			
			eventRegister.setAcceptLimitSpan(eventType.getAcceptLimit());
			eventRegister.setDealLimitSpan(eventType.getProcessLimit());
			
			List<Option> state = optionService.getRepository().findByGroupAndTitle("内部事件流转状态", "已分配");
			if (state != null && state.size() > 0) {
				eventRegister.setRegisterEventState(state.get(0));
			} else {
				map.put("code", "未知错误");
				return map;
			}
			if (request.getParameter("eventSeriousLevel") != null) {
				List<Option> serious = optionService.getRepository().findByGroupAndTitle("事件严重等级", URLDecoder.decode(request.getParameter("eventSeriousLevel"),"utf-8"));
				if (serious != null && serious.size() > 0) {
					eventRegister.setRegisterEventSeriousLevel(serious.get(0));
				} else {
					map.put("code", "事件严重等级错误");
					return map;
				}
			}
			
			Grading EvaluateLevel = null;
			if(gridAreaInfo != null) {
				List<Grading> gradings= this.gridUserDetailsService.getRepository().getGradingByGrid(gridAreaInfo.getId());
				if(gradings!=null&&gradings.size()>0){
					gradings.sort((Grading g1, Grading g2) -> g1.getGradingLevel().getExtended1().compareTo(g2.getGradingLevel().getExtended1()));	
					for(Grading grading : gradings) {
						if(grading.getGradingLevel().getExtended1().equals("3")) {
							EvaluateLevel = grading;
						}
					}
					if(EvaluateLevel == null) {
						map.put("code", "事件扣分登记错误");
						return map;
					}
				}else {
					map.put("code", "事件扣分登记错误");
					return map;
				}
			}else {
				map.put("code", "网格信息错误");
				return map;
			}
			String areaId = "";
			if(gridAreaInfo.getDivision() != null) {
				areaId = gridAreaInfo.getDivision().getId();
			}
			String eventIdentify=this.identifyService.getEventIdentifyByGridAndEventType(areaId, eventType.getId());
			eventRegister.setRegisterEventIdentify(eventIdentify);
			eventRegister.setRegisterEventEvaluateLevel(EvaluateLevel);
			
			// 事件源上报的日志信息
			EventTask registerTask = new EventTask();
			registerTask.setEventId(eventRegister.getId());
			registerTask.setEventTaskMemo(eventRegister.getRegisterEventMemo());
			registerTask.setEventTaskOperate("初始化智能部件上报事件");
			registerTask.setEventTaskState(eventRegister.getRegisterEventState());
			registerTask.setEventTaskTime(accTime);
			registerTask.setEventTaskUser(user);
			
			List<List<UserSingle>> users=this.eventRegisterService.findUserSingle(EvaluateLevel.getId(), eventType.getId(),gridAreaInfo.getId() );
			List<EventToEvaluateUser> dlist = new ArrayList<>();
			for(List<UserSingle> lst: users) {
				for(UserSingle us: lst) {
					EventToEvaluateUser eventToEvaluateUser = new EventToEvaluateUser();
					BigDecimal b = new  BigDecimal(us.scale);  
					double f = b.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
					User u = userService.getRepository().findOne(us.id);
					eventToEvaluateUser.setScale(f);
					eventToEvaluateUser.setRegisterEvent(eventRegister);
					eventToEvaluateUser.setRegisterUser(u);
					Grading g = gradingService.getRepository().findOne(us.eventToevaluateId);
					eventToEvaluateUser.setRegisterEventEvaluateLevel(g);
					dlist.add(eventToEvaluateUser);
				}
				
			}
			
			eventReportOuterService.saveAll(eventReport, reportTask, eventRegister, registerTask , dlist);
			this.operateLogService.log(user, "接口上报", "智能部件上报:"+eventReport.getReportAccTime().toString()+",发生:"+eventReport.getReportEventType().getEventName()+",详细情况:"+eventReport.getReportContent()+",地点:"+eventReport.getReportAdress()+"经度:"+eventReport.getLongitude()+",纬度:"+eventReport.getLatitude());
		} catch (Exception ex) {
			map.put("code", "未知错误");
			return map;
		}
		
		map.put("code", "上报成功");
		return map;
	}
}
